/*
*	Communicate timed messages with the server
*/


//general ajax function for all requests 
function makeRequest(url,async) {
	var httpRequest;
	if (window.XMLHttpRequest) {
		// Mozilla, Safari, ...
		httpRequest = new XMLHttpRequest();
	} else if (window.ActiveXObject) {
		// IE
		try {
			httpRequest = new ActiveXObject("Msxml2.XMLHTTP");
		} 
		catch (e) {
			try {
				httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
			} 
			catch (e) {}
		}
	}

	if (!httpRequest) {
		alert('Cannot create an XMLHTTP instance');
		return false;
	}
	httpRequest.open('POST', url,async);
	httpRequest.send();
	return httpRequest;
}

function trigger(psID,vidId,time) {
	var sendMessageURI = '/comm?code=1&psId=' + psID + '&vidId=' + vidId + '&time=' + time ;
	makeRequest(sendMessageURI,true);
}

function checkTime() {
	if (player.getPlayerState() == 1) {
		var vidTime = parseInt(player.getCurrentTime());
		//Sends message to server at set time interval
		if (times.indexOf(vidTime) != -1) {
			trigger(playerScreenID,videoId,vidTime);
		}
	}
}

//Receiving messages
requestToken = function(){
	var channelCookieExists = new Boolean(document.cookie.indexOf("chtoken") >= 0);
	if (channelCookieExists==true) {
		//Use the cookie's data
		openChannel(readCookie("chtoken"));
	} else {
		var getTokenURI = '/gettoken?userId=' + playerScreenID ;
		var httpRequest = makeRequest(getTokenURI,true);
		httpRequest.onreadystatechange = function(){
			if (httpRequest.readyState === 4) {
				if (httpRequest.status === 200) {
					//Create the cookie
					writeCookie("chtoken",httpRequest.responseText,(2/24));
					//Open the channel
					openChannel(httpRequest.responseText);
				}
			}
		}
	}
};

openChannel = function(token) {
	var channel = new goog.appengine.Channel(token);
	var socket = channel.open();
	socket.onopen = onSocketOpen;
	socket.onmessage = onSocketMessage;
	socket.onerror = onSocketError;
	socket.onclose = onSocketClose;
};

onSocketError = function(error){
	requestToken();
	var sendMessageURI = '/logger?code=3&status=ChannelSocketErrorComm';
	makeRequest(sendMessageURI,true);
};

onSocketOpen = function() {
	// socket opened
};

onSocketClose = function() {
	requestToken();
	var sendMessageURI = '/logger?code=2&status=ChannelSocketCloseComm';
	makeRequest(sendMessageURI,true);
};

onSocketMessage = function(message) {
	var messageXML = ((new DOMParser()).parseFromString(message.data, "text/xml"));
	var messageType = messageXML.documentElement.getElementsByTagName("type")[0].firstChild.nodeValue;
	if (messageType == "updateMessage") {
		vidId = messageXML.documentElement.getElementsByTagName("vidId")[0].firstChild.nodeValue;
		newURL = "/play.jsp?videoId=" + vidId;
		window.location = newURL;
	} else if (messageType == "play") {
		if (player.getPlayerState() != 1) {
			player.playVideo();
		} else {
			player.stopVideo();
		}
	}
};